package com.dongjiantong.openplatform.core;/**
 * Created by cao on 2017/12/13.
 */

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * @author cao
 * @create 2017-12-13 下午8:26
 **/
@Component
public class OPEventDispatcher {
    private static final Logger log = LoggerFactory.getLogger(OPEventDispatcher.class);
    protected final EventBus eventBus;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private OPInvoker invoker;
    @Autowired
    private SecurityManager securityManager;
    @Autowired(
            required = false
    )
    private List<PushPostHandle> pushPostHandles;
    @Autowired
    private OpenProperties openProperties;

    public OPEventDispatcher() {
        this(Integer.valueOf(Runtime.getRuntime().availableProcessors() + 1));
    }

    public OPEventDispatcher(Integer threadCount) {
        this.eventBus = new AsyncEventBus(Executors.newFixedThreadPool(threadCount.intValue()));
    }

    @PostConstruct
    public void registerListeners() {
        this.eventBus.register(new OPEvenSubscriber(this.invoker, this.securityManager, this.pushPostHandles, this.openProperties));
    }

    public void publish(Object event) {
        log.info("publish an event({})", event);
        this.eventBus.post(event);
    }
}
